//
//  LoginView.m
//  BORGWORD
//
//  Created by 张国庆 on 15/11/17.
//  Copyright © 2015年 zgq. All rights reserved.
//

#import "LoginView.h"
#import "LoadingView.h"
#import "borgword_define.h"
#import "UIAlertViewControl.h"
#import "MyAFNetWorkManager.h"


@implementation LoginView
@synthesize salerInfo;
static LoginView* s_loginView = nil;

+ (LoginView*)shareInstance
{
    if (nil == s_loginView)
    {
        s_loginView = [[LoginView alloc] init];
        
    }
    return s_loginView;
}


- (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    //CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    CC_LONG    md5=(CC_LONG)strlen(cStr);
    CC_MD5(cStr,md5, result);
    NSString *lognstr=[NSString stringWithFormat:
                       @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                       result[0], result[1], result[2], result[3],
                       result[4], result[5], result[6], result[7],
                       result[8], result[9], result[10], result[11],
                       result[12], result[13], result[14], result[15]
                       ];
    
    return [lognstr substringToIndex:24];
}


-(void)awakeFromNib
{
    loginViewFrame=self.myLoginView.frame;
    self.dealerArr=[NSMutableArray array];
    
    _siteBtn.layer.borderWidth=1;
    _siteBtn.layer.borderColor=[UIColor colorWithWhite:(0xda / 255.0) alpha:1].CGColor;

    _userNameTextField.layer.borderWidth=1;
    _userNameTextField.layer.borderColor=[UIColor colorWithWhite:(0xda / 255.0) alpha:1].CGColor;
    
    
    self.passWordTextField.layer.borderWidth=1;
    self.passWordTextField.layer.borderColor=[UIColor colorWithWhite:(0xda / 255.0) alpha:1].CGColor;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    if([[user objectForKey:@"ENTITY_NAME"]length]>0)
    {
        [self.siteBtn setTitle:[user objectForKey:@"ENTITY_NAME"] forState:UIControlStateNormal];
        self.ENTITY_CODE=[user objectForKey:@"ENTITY_CODE"];
    }
}


-(void)keyboardShow:(NSNotification *)note
{
    for(id view in self.subviews)
    {
        if([view isFirstResponder])
        {
            pt = [view convertPoint:CGPointMake(0, 0) toView:self.superview];
            NSLog(@"%@",[NSValue valueWithCGPoint:pt]);
            break;
        }
        else if([view isKindOfClass:[UIView class]])
        {
            UIView *myview=(UIView *)view;
            for(id subview in myview.subviews)
            {
                if([subview isFirstResponder])
                {
                    pt = [subview convertPoint:CGPointMake(0, 0) toView:self.superview];
                }
            }
        }
    }
    CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat deltaY=keyBoardRect.size.height;
    keyBordHeight=deltaY;
    
    float yWill = UISCREEN_BOUNDS_HEIGHT-deltaY;
    float h=pt.y+60 -yWill-middleH;
    if(h<0)
    {
        return;
    }
    [UIView animateWithDuration:0.3 animations:^{
        
        CGRect fram_bar=self.myLoginView.frame;
        float y=fram_bar.origin.y-h;
        fram_bar.origin.y=y;
        self.myLoginView.frame=fram_bar;
        
    } completion:^(BOOL finished)
    {
        if (finished) {
            middleH+=h;
        }
    }];
}

-(void)keyboardHide:(NSNotification*)note
{
    [UIView animateWithDuration:0.3 animations:^{
        
        self.myLoginView.frame=loginViewFrame;
        
    } completion:^(BOOL finished)
    {
        if (finished) {
            middleH=0;
        }
    }];
}


-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.superview endEditing:YES];
}


//站点
- (IBAction)siteBtnClicked:(id)sender
{
    _WEAK_SELF
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSData *dealerdata=[user objectForKey:@"dealerdata"];
    self.dealerArr = [NSKeyedUnarchiver unarchiveObjectWithData:dealerdata];
    if([self.dealerArr count]>0)
    {
        if(!_myview)
        {
            CGRect rectBtn=self.siteBtn.frame;
            CGRect viewframe=CGRectMake(rectBtn.origin.x, rectBtn.origin.y+rectBtn.size.height+2, rectBtn.size.width, 0);
            _myview=[[DealerView alloc]initWithFrame:viewframe andArr:self.dealerArr andSuperView:self.myLoginView];
            _myview.selectBlock=^(DealerModle *dealer)
            {
                [weakSelf.siteBtn setTitle:dealer.AscName forState:UIControlStateNormal];
                weakSelf.ENTITY_CODE=dealer.EntityCode;
                weakSelf.ENTITY_NAME=dealer.AscName;
                _myview=nil;
            };
        }
        else
        {
            [_myview removeFromSuperview];
            _myview =nil;
        }
    }
    else
    {
        [UIAlertViewControl showAlertView:self.viewController WithMes:@"经销商列表为空，请检查IP设置" andWithCancel:@"确定"];
    }
}


- (IBAction)AutomaticLoginBtnClicked:(id)sender
{
    UIButton *btn=(UIButton*)sender;
    btn.selected=!btn.selected;
}

- (IBAction)IPBtnClicked:(id)sender
{
    if(self.setipBlock)
    {
        self.setipBlock();
    }
}

- (IBAction)loginBtnClicked:(id)sender
{
    if(self.ENTITY_CODE.length<=0)
    {
        [UIAlertViewControl showAlertView:self.viewController WithMes:@"经销商不能为空" andWithCancel:@"确定"];
        return;
    }
    if(self.userNameTextField.text.length<=0)
    {
        [UIAlertViewControl showAlertView:self.viewController WithMes:@"用户名不能为空" andWithCancel:@"确定"];
        return;
    }
    if(self.passWordTextField.text.length<=0)
    {
        [UIAlertViewControl showAlertView:self.viewController WithMes:@"密码不能为空" andWithCancel:@"确定"];
        return;
    }
    NSDictionary *dic=@{
                        @"ENTITY_CODE":self.ENTITY_CODE,
                        @"USER_CODE":self.userNameTextField.text,
                        @"PASSWORD":[self md5:self.passWordTextField.text],
                        @"PAD_LOGIN":@"12781001"
                        
                        };
    _WEAK_SELF
    [[LoadingView sharedView]loadingViewWithsuperView:self];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //api调用及返回
        [MyAFNetWorkManager postWithParam:dic andAction:action_Login finish:^(NSData *data, NSDictionary *obj, NSError *error) {
            [[LoadingView sharedView]dismissFromSupview];
            if (error == nil)
            {
                //obj即为解析后的数据.
                
                NSLog(@"parase my download json is %@",obj);
                
                if([[obj valueForKey:@"SUCCESS"]integerValue]==1)
                {
                
                    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
                    
                    [user setObject:[obj valueForKey:@"USER_ID" ] forKey:@"userId"];
                    [user setObject:self.ENTITY_CODE forKey:@"ENTITY_CODE"];
                    [user setObject:self.ENTITY_NAME forKey:@"ENTITY_NAME"];
                    [user setObject:self.userNameTextField.text forKey:@"userName"];
                    [user setObject:[self md5:self.passWordTextField.text] forKey:@"passWord"];
                    [user setObject:[obj objectForKey:@"USER_NAME"] forKey:@"USER_NAME"];
                    [user setObject:@"YES" forKey:@"IsLoginSuccess"];
                    
                    [user synchronize];

                    NSLog(@"userId----%@",[user valueForKey:@"userId"]);
                    
                    if(weakSelf.loginBlock)
                    {
                        weakSelf.loginBlock();
                    }

                    if (_delegate && [_delegate respondsToSelector:@selector(loginInSuccess)])
                    {
                        [_delegate  loginInSuccess];
                    }
                    [weakSelf removeFromSuperview];
                }
                else
                {
                    
                }
                
            }
            else
            {
                
                NSLog(@"%@",error);
            }
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    });
    
}



@end
